package com.jzoom.zoom.admin.models;

import com.jzoom.zoom.common.Destroyable;
import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.common.designpattern.SingletonUtils;
import com.jzoom.zoom.common.designpattern.SingletonUtils.SingletonInit;
import com.jzoom.zoom.common.utils.Classes;
import com.jzoom.zoom.dao.Dao;
import com.jzoom.zoom.dao.Record;
import com.jzoom.zoom.dao.impl.ZoomDao;
import com.jzoom.zoom.dao.provider.DruidDataSourceProvider;
import com.jzoom.zoom.web.exception.StatusException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DaoService implements Destroyable {

	@Inject(value = "admin")
	private Dao sysDao;
	
	
	private Map<String, Dao> map = new ConcurrentHashMap<String, Dao>();
	@Override
	public void destroy() {
		clear();
	}
	
	
	public void clear() {
		Classes.destroy(map);
	}
	
	public Dao getDao(final String key) {
		if(key==null)
		{
			throw new NullPointerException();
		}
		
		final String name = key.toLowerCase();
		
		if("sys".equals(name)) {
			return sysDao;
		}
		

		return SingletonUtils.liteDoubleLockMap(map, name, new SingletonInit<Dao>() {

			@Override
			public Dao create() {
				 
				Record record = sysDao.ar().table("sys_datasource").where("key", name).get();
				if(record==null) {
					throw new StatusException.ApiError("dao名称"+name+"不存在");
				}
				//create
				
				DruidDataSourceProvider provider =new DruidDataSourceProvider();
				provider.setDriverClassName(record.getString("driver"));
				provider.setPassword(record.getString("pwd"));
				provider.setUrl(record.getString("url"));
				provider.setUsername(record.getString("user"));
				
				return  new ZoomDao(provider.getDataSource());
				
			}
		});
		
	}
	
	

	
}
